using ProtoBuf;
using SuperSocket.ProtoBase;

namespace Core;

public abstract class PlayPacket : IKeyedPackageInfo<CommandKey>
{
    internal static readonly Dictionary<CommandKey, Type> CommandTypes = new();

    static PlayPacket()
    {
        var typeArray = typeof(PlayPacket).Assembly.GetTypes();

        foreach (var classType in typeArray)
        {
            var command = classType.GetCustomAttributes(true)
                .OfType<CommandKeyAttribute>()
                .FirstOrDefault();

            if (command == null)
                continue;

            CommandTypes.TryAdd(command.Key, classType);
        }
    }

    public CommandKey Key { get; set; }

    public virtual ReadOnlySpan<byte> EncodeBody()
    {
        using var stream = new MemoryStream();

        Serializer.Serialize(stream, this);

        return stream.ToArray();
    }
}

public abstract class PlayPacketWithIdentifier : PlayPacket
{
    public abstract ushort Identifier { get; set; }
}

// [ProtoContract]
// public class BasePacket
// {
//     /// <summary>
//     /// 命令
//     /// </summary>
//     [ProtoMember(1)]
//     public CommandKey Key { get; set; }
//
//     /// <summary>
//     ///内容
//     /// </summary>
//     [ProtoMember(2)]
//     public byte[]? Body { get; set; }
//
//     /// <summary>
//     /// 错误代码
//     /// </summary>
//     [ProtoMember(3)]
//     public ErrorCode ErrorCode { get; set; }
//
//     /// <summary>
//     /// 错误消息
//     /// </summary>
//     [ProtoMember(4)]
//     public string? ErrorMessage { get; set; }
//
//     /// <summary>
//     /// 包id
//     /// </summary>
//     [ProtoMember(5)]
//     public ulong Identifier { get; set; }
//
//     /// <summary>
//     /// 是否成功
//     /// </summary>
//     public bool SuccessFul => ErrorCode == ErrorCode.None;
// }
//
// [ProtoContract]
// public class BasePacket<TBody> : BasePacket
//     where TBody : class
// {
//     public BasePacket()
//     {
//     }
//
//     public BasePacket(TBody body)
//     {
//         Body = body;
//     }
//
//     /// <summary>
//     /// 命令
//     /// </summary>
//     [ProtoMember(1)]
//     public CommandKey Key { get; set; }
//
//     /// <summary>
//     ///内容
//     /// </summary>
//     [ProtoMember(2)]
//     public new TBody Body { get; set; }
//
//     /// <summary>
//     /// 错误代码
//     /// </summary>
//     [ProtoMember(3)]
//     public ErrorCode ErrorCode { get; set; }
//
//     /// <summary>
//     /// 错误消息
//     /// </summary>
//     [ProtoMember(4)]
//     public string? ErrorMessage { get; set; }
//
//     /// <summary>
//     /// 包id
//     /// </summary>
//     [ProtoMember(5)]
//     public ulong Identifier { get; set; }
//
//     /// <summary>
//     /// 是否成功
//     /// </summary>
//     public bool SuccessFul => ErrorCode == ErrorCode.None;
// }